package com.sunxd.disruptor.test;

/**
 * 应对java8 的实现，使用EventTranslator
 * @author: 作者名称
 * @date: 2021-09-27 09:51
 **/

import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.Disruptor;
import com.sunxd.disruptor.event.LongEvent;
import com.sunxd.disruptor.factory.LongEventFactory;
import com.sunxd.disruptor.handler.LongEventHandler;

import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class Run2 {
    public static void main(String[] args) {
        LongEventFactory factory = new LongEventFactory();
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(factory,1024, Executors.defaultThreadFactory());
        disruptor.handleEventsWith(new LongEventHandler());
        disruptor.start();
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        // 比较固定的写法
        EventTranslator<LongEvent> translator1 = new EventTranslator<LongEvent>() {
            @Override
            public void translateTo(LongEvent longEvent, long l) {
                longEvent.setValue(0L);
            }
        };
        ringBuffer.publishEvent(translator1);


        // 允许传入一个参数
        EventTranslatorOneArg<LongEvent,Long> translatorOneArg = new EventTranslatorOneArg<LongEvent, Long>() {
            @Override
            public void translateTo(LongEvent longEvent, long sequence, Long aLong) {
                longEvent.setValue(aLong);
            }
        };
        ringBuffer.publishEvent(translatorOneArg,11L);

        // 允许传入2个参数
        EventTranslatorTwoArg<LongEvent,Long ,Long> eventEventTranslatorTwoArg = new EventTranslatorTwoArg<LongEvent,Long,Long>(){
            @Override
            public void translateTo(LongEvent longEvent, long l, Long aLong, Long aLong2) {
                longEvent.setValue(aLong+aLong2);
            }
        };
        ringBuffer.publishEvent(eventEventTranslatorTwoArg,2L,22L);

        // 允许传入N个参数
        EventTranslatorVararg<LongEvent> eventEventTranslatorVararg = new EventTranslatorVararg<LongEvent>() {
            @Override
            public void translateTo(LongEvent longEvent, long l, Object... objects) {

                longEvent.setValue(Arrays.stream(objects).mapToLong( x -> Long.parseLong( String.valueOf(x))).sum());
            }
        };
        ringBuffer.publishEvent(eventEventTranslatorVararg,11,22,33);

    }
}
